<?php

/**
 * $Id: IndexController.php 423 2008-05-30 14:42:41Z dakl $
 * Strona glowna
 *
 */
class ShopController extends MainController implements ControllerInterface {

    //o - order
    //v - order vector
    //t - total items to select
    public $tableConfig = array(
        'shop_table_main' => array(
            'o' => array(
                'id' => 'shop.id_shop',
                'name' => 'shop.name',
                '_' => 'id'
            ),
            'v' => 'malejaco',
            't' => 10
        ),
        'product_table_main' => array(
            'o' => array(
                'id' => 'product.id_product',
                'serial' => 'product.code',
                'name' => 'product_description.name',
                '_' => 'id'
            ),
            'v' => 'malejaco',
            't' => 10
        )
    );

    /**
     * strona glowna
     *
     */
    public function IndexAction($param) {
        $lang = Registry::Get('default_language_id');
        $dal = ShopDAL::GetDalDataObj(array(
                    'tableData' => $this->tableParams['shop_table_main']
                ));

        if (Request::IsPost() && Request::Check('id_manufacturer')) {
            $data = Request::GetAllPost();
            SessionProxy::SetValue('product_filter', serialize($data));
            $this->addRedirect(Router::GenerateUrl('productIndex', array('product' => 'index')), 0);
        }

        if (SessionProxy::IsSetValue('shop_filter')) {
            $data = SessionProxy::GetValue('shop_filter');
            $data = unserialize($data);

            $filtering = false;

            if ($data['id_manufacturer'] > 0) {
                $dal->addCondition('id_manufacturer', $data['id_manufacturer']);
                $filtering = true;
            }

            if ($data['id_category'] > 0) {
                $dal->addCondition('id_category', $data['id_category']);
                $filtering = true;
            }

            if (strlen($data['code']) > 0) {
                $dal->addCondition('code', $data['code']);
                $filtering = true;
            }

            if (strlen($data['name']) > 0) {
                $dal->addCondition('product_description.name', "'%" . $data['name'] . "%'", 'LIKE');
                $filtering = true;
            }

            if ($filtering) {
                $this->smarty->assign('filter', $data);
            } else {
                SessionProxy::ClearValue('product_filter');
            }
        }

        $list = ShopDAL::GetResult($dal);
        $dal->setCount(true);
        $dal->setLimit('');
        $count = ShopDAL::GetResult($dal);

        $this->smarty->assign('list', $list);
        $this->smarty->assign('c', $count);
    }

    public function ProductsAction($param) {
        $lang = Registry::Get('default_language_id');
        $dal = ProductDAL::GetDalDataObj(array(
                    'tableData' => $this->tableParams['product_table_main'],
                    'join' => array(
                        'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')',
                        'ProductShop' => ' INNER JOIN product_shop ON(product.id_product = product_shop.id_product)'
                    )
                ));
        $dal->addCondition('id_shop', $param['id']);

        if (Request::IsPost() && Request::Check('id_manufacturer')) {
            $data = Request::GetAllPost();
            SessionProxy::SetValue('product_filter', serialize($data));
            $this->addRedirect(Router::GenerateUrl('productIndex', array('product' => 'index')), 0);
        }

        if (SessionProxy::IsSetValue('product_filter')) {
            $data = SessionProxy::GetValue('product_filter');
            $data = unserialize($data);

            $filtering = false;

            if ($data['id_manufacturer'] > 0) {
                $dal->addCondition('id_manufacturer', $data['id_manufacturer']);
                $filtering = true;
            }

            if ($data['id_category'] > 0) {
                $dal->addCondition('id_category', $data['id_category']);
                $filtering = true;
            }

            if (strlen($data['code']) > 0) {
                $dal->addCondition('code', $data['code']);
                $filtering = true;
            }

            if (strlen($data['name']) > 0) {
                $dal->addCondition('product_description.name', "'%" . $data['name'] . "%'", 'LIKE');
                $filtering = true;
            }

            if ($filtering) {
                $this->smarty->assign('filter', $data);
            } else {
                SessionProxy::ClearValue('product_filter');
            }
        }

        $list = ProductDAL::GetResult($dal);
        $dal->setCount(true);
        $dal->setLimit('');
        $count = ProductDAL::GetResult($dal);

        $this->smarty->assign('list', $list);
        $this->smarty->assign('c', $count);
    }

    public function RemoveProductAction($param) {
        $this->setNoRender();
        $imageMap = ProductShopDAL::GetResult(ProductShopDAL::GetDalDataObj(array('condition' => array('id_product_shop' => array($param['id'])))));

        $id = 0;

        foreach ($imageMap AS $item) {

            ProductShopDAL::Delete($item->getDalDataObj());
        }

        $this->addRedirect(Router::Generateurl('', array('Shop' => 'Index')), 0);
    }

    public function EditAction($param) {
        $idShop = $param['id'];
        $dalObj = ShopDAL::GetDalDataObj();
        $dalObj->setId($idShop);
        $shop = ShopDAL::GetById($dalObj);

        $this->smarty->assign('shop', $shop);

        $dalObj = ShopUserDAL::GetDalDataObj();
        $dalObj->addCondition('id_shop', $shop->getId());
        $dalObj->setLimit('1');
        $shopUser = ShopUserDAL::GetResult($dalObj);
        if (isset($shopUser[0])) {
            $this->smarty->assign('shopUser', $shopUser[0]);
            $shopUser = $shopUser[0];
        } else {
            $shopUser = new ShopUser();
        }

        if (Request::IsPost() && Request::Check('name')) {
            $shop->setName(Request::GetPost('name'));
            $shop->setActive(Request::GetPost('active'));
            $shop->setUrl(Request::GetPost('url'));
            $shop->setFirstName(Request::GetPost('first_name'));
            $shop->setLastName(Request::GetPost('last_name'));
            $shop->setStreet(Request::GetPost('street'));
            $shop->setHouseNumber(Request::GetPost('house_number'));
            $shop->setLocalNumber(Request::GetPost('local_number'));
            $shop->setZipCode(Request::GetPost('zip_code'));
            $shop->setCity(Request::GetPost('city'));
            $shop->setCountry(Request::GetPost('country'));
            $shop->setNip(Request::GetPost('nip'));
            $dalObj = ShopDAL::GetDalDataObj();
            
            
            
            if(isset($_FILES['logo']) && is_uploaded_file($_FILES['logo']['tmp_name'])) {
                
				$img = imagecreatefromstring(file_get_contents($_FILES['logo']['tmp_name']));
				if($img !== false) { 
					if(!is_dir(PATH_STATIC_CONTENT . 'upload/shop'))
						mkdir(PATH_STATIC_CONTENT . 'upload/shop',0777,true);

					$fileName = preg_replace('~[^\\pL\d\.]+~u', '-', $_FILES['logo']['name']);

					$temp = $fileName;
					$counter = 0;
					while(is_file(PATH_STATIC_CONTENT . 'upload/shop/'.$temp))
						$temp = ++$counter.'_'.$fileName;

					$fileName = $temp;
					
					move_uploaded_file($_FILES['logo']['tmp_name'], PATH_STATIC_CONTENT . 'upload/shop/' . $fileName);
					$shop->setLogo('upload/shop/' . $fileName);
				}
                                
			}
            
            
            $dalObj->setObj($shop);
            ShopDAL::Save($dalObj);
            $dalObj = ShopUserDAL::GetDalDataObj();
            if (Request::Check('password')) {
                $shopUser->setLogin(Request::GetPost('login'));
                $shopUser->setPassword(md5(Request::GetPost('password')));
                $shopUser->setIdShop($shop->getId());
                $shopUser->setActive('1');
                $dalObj->setObj($shopUser);
                ShopUserDAL::Save($dalObj);
            }
            $this->addRedirect(Router::Generateurl('', array('Shop' => 'Index')), 0);
        }
    }

    public function AddAction($param) {




        if (Request::IsPost() && Request::Check('name')) {

            $dalObj = ShopDAL::GetDalDataObj();

            $shop = new Shop();


            $dalObj = ShopUserDAL::GetDalDataObj();


            $shopUser = new ShopUser();


            $shop->setName(Request::GetPost('name'));
            $shop->setActive(Request::GetPost('active'));
            $shop->setUrl(Request::GetPost('url'));
            $shop->setFirstName(Request::GetPost('first_name'));
            $shop->setLastName(Request::GetPost('last_name'));
            $shop->setStreet(Request::GetPost('street'));
            $shop->setHouseNumber(Request::GetPost('house_number'));
            $shop->setLocalNumber(Request::GetPost('local_number'));
            $shop->setZipCode(Request::GetPost('zip_code'));
            $shop->setCity(Request::GetPost('city'));
            $shop->setCountry(Request::GetPost('country'));
            $shop->setNip(Request::GetPost('nip'));
            $dalObj = ShopDAL::GetDalDataObj();
            
            if(isset($_FILES['logo']) && is_uploaded_file($_FILES['logo']['tmp_name'])) {
                
				$img = imagecreatefromstring(file_get_contents($_FILES['logo']['tmp_name']));
				if($img !== false) { 
					if(!is_dir(PATH_STATIC_CONTENT . 'upload/shop'))
						mkdir(PATH_STATIC_CONTENT . 'upload/shop',0777,true);

					$fileName = preg_replace('~[^\\pL\d\.]+~u', '-', $_FILES['logo']['name']);

					$temp = $fileName;
					$counter = 0;
					while(is_file(PATH_STATIC_CONTENT . 'upload/shop/'.$temp))
						$temp = ++$counter.'_'.$fileName;

					$fileName = $temp;
					
					move_uploaded_file($_FILES['logo']['tmp_name'], PATH_STATIC_CONTENT . 'upload/shop/' . $fileName);
					$shop->setLogo('upload/shop/' . $fileName);
				}
                                
			}
            
            $dalObj->setObj($shop);
            $id = ShopDAL::Save($dalObj);
            $dalObj = ShopUserDAL::GetDalDataObj();
            if (Request::Check('password')) {
                $shopUser->setLogin(Request::GetPost('login'));
                $shopUser->setPassword(md5(Request::GetPost('password')));
                $shopUser->setIdShop($id);
                $shopUser->setActive('1');
                $dalObj->setObj($shopUser);
                ShopUserDAL::Save($dalObj);
            }
            $this->addRedirect(Router::Generateurl('', array('Shop' => 'Index')), 0);
        }
    }

    public function EditProductAction($param) {
        $this->AddDescription('');
        $this->AddTitle(' ');
        $product = ProductShopDAL::GetResult(ProductShopDAL::GetDalDataobj(array('condition' => array(
                                'id_product_shop' => array($param['id'])
                                ))));
        $product = $product[0];

        //var_dump($product);

        $dal = ProductDAL::GetDalDataObj(array(
                    //'tableData' => $this->tableParams['product_table_main'],
                    'join' => array(
                        'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')'
                    )
                ));
        $this->smarty->assign('products', ProductDAL::GetResult($dal));

        $this->view->obj = $product;

        if (Request::IsPost()) {

            $data = Request::GetAllPost();
            if (isset($data['id_product'])) {
                //$product = new ProductShop();
                $product->setIdProduct($data['id_product']);
                $product->setActive($data['active']);
                $product->setPrice($data['price']);
                //$product->setIdShop();
                $product->setUrl($data['url']);
                $dalObj = ProductShopDAL::GetDalDataObj();
                $dalObj->setObj($product);
                $id_product = ProductShopDAL::Save($dalObj);
            }

            if (isset($data['name']) && is_array($data['name'])) {
                foreach (array_keys($data['name']) AS $id_language) {
                    $productDescription = $product->getDescription($id_language);
                    $productDescription->setIdProductShop($id_product);
                    $productDescription->setIdLanguage($id_language);
                    //$productDescription->setDescription(Request::GetPost('description_'.$id_language,false));
                    //$productDescription->setTechnologies(Request::GetPost('technologies_'.$id_language,false));
                    $productDescription->setName($data['name'][$id_language]);
                    //$productDescription->setSeoKeywords($data['seo_keywords'][$id_language]);
                    //$productDescription->setSeoDescription($data['seo_description'][$id_language]);
                    ProductShopDescriptionDAL::Update($productDescription->getDalDataObj());
                }
            }

            $this->addRedirectInfo('Zmiany zostały zapisane', 'ok', Router::GenerateUrl('', array('Shop' => 'Products', 'id' => $product->getIdShop())), 0);
        }



        $this->smarty->assign('obj', $product);
    }

    /**
     * Metoda wspolna
     *
     */
    public function preDispatch($param) {
        $this->RunShared('Auth');
        $this->Run();
        $this->smarty->assign('param_from_url', $param);
        $this->smarty->assign('languages', LanguageDAL::GetResult(LanguageDAL::GetDalDataobj(array('sortBy' => 'id_language ASC', 'condition' => array('active' => '1')))));
        $this->smarty->assign('manufacturers', ManufacturerDAL::GetResult(ManufacturerDAL::GetDalDataObj(array('sortBy' => 'name ASC', 'condition' => array('active' => array('value' => 1))))));
        $this->smarty->assign('categories', CategoryDAL::getAdminCategoryTree());
    }

    /**
     * 
     *
     */
    public function postDispatch($param) {
        
    }

}
